<template>
  <view class="word-learning-page">
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view>
        <text>{{ title }}</text>
      </view>
      <view class="top-nav__right">
        <!-- 发音切换 (美式/英式) -->
        <u-button
            class="nav-btn accent-btn"
            :custom-style="accentBtnStyle"
            @click="toggleAccent"
        >
          <text>{{ isAmerican ? '美音' : '英音' }}</text>
        </u-button>

        <!-- 音标显示/隐藏 -->
        <u-button
            class="nav-btn phonetic-btn"
            :custom-style="phoneticBtnStyle"
            @click="togglePhonetic"
        >
          <text :class="['phonetic-label', { 'is-off': !showPhonetic }]">音标</text>
        </u-button>
      </view>
    </view>

    <!-- 中间滚动列表区域 -->
    <scroll-view class="word-list-container" scroll-y @scrolltolower="loadMore">
      <view v-if="displayedWords.length > 0" class="word-list">
        <view
            v-for="(word, index) in displayedWords"
            :key="index"
            class="word-item"
            :class="{
            'word-known': word.status === 'known',
            'word-unknown': word.status === 'unknown'
          }"
            @click="playPronunciation(word, index)"
        >
          <!-- 单词和音标 -->
          <view class="word-info">
            <view class="word-main">
              <view class="word-text">
                <text
                    @click.stop="playEn(word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : 'I don\'t know')"
                >{{ word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : '🤔' }}
                </text>
              </view>
              <text v-if="showPhonetic" class="word-phonetic">
                {{ isAmerican ? word.phoneticAm : word.phoneticBr }}
              </text>

              <!-- 单词意思 -->
              <view v-if="word.clickCount % 3 === 2" class="word-meaning">
                <text @click.stop="playZh(word.wordMeaning.replace(/[A-Za-z]/g, ''))">{{ word.wordMeaning }}</text>
              </view>
            </view>

            <!-- 添加短语例句按钮 -->
            <view class="phrase-btn-wrap">
              <i class="fa-solid fa-book-open" v-if="word.extendedInfo" @click.stop="showPhraseExample(word)"></i>
              <i class="fa-solid fa-delete-left" v-if="showType === 'forgotten'"
                 @click.stop="deleteCollectWord(word)"></i>
            </view>
          </view>
        </view>
        <view v-if="loading" style="text-align:center;padding:10px;color:#999">
          加载中...
        </view>
        <view v-else-if="finished" style="text-align:center;padding:10px;color:#999">
          已加载全部内容
        </view>
      </view>
      <view v-else>
        <u-empty text="这里空空的" mode="list"></u-empty>
      </view>
    </scroll-view>

    <word-detail-drawer
        :word="currentWordDetail"
        :visible="drawer"
        @update:visible="drawer = false"
        style="max-height: 0px"
    />
  </view>
</template>

<script>
import AudioCacheUtil from '@/utils/AudioCacheUtil'
import {antiForgetListPush} from '@/api/antiForget'
import WordDetailDrawer from '@/pages/components/WordDetailDrawer.vue'
import View from "../component/view/view.vue";
import {getWordListByType} from "../../api/enStudent";
import {deleteCollectById} from "../../api/antiForgetCollectWord";

export default {
  name: 'AntiForgetReview',
  components: {View, WordDetailDrawer},
  data() {
    return {
      isAmerican: true, // 美式发音
      showPhonetic: true, // 显示音标
      playbackSpeed: 1.0, // 播放速度

      // 单词数据
      displayedWords: [], // 显示的单词

      nowClickWord: {},
      currentWordDetail: {},
      drawer: false,

      page: {
        pageNum: 1,
        pageSize: 20
      },
      total: 0, // 数据总条数
      loading: false, // ✅ 是否正在加载中
      finished: false // ✅ 是否已加载完所有数据
    }
  },
  computed: {
    accentBtnStyle() {
      return {
        padding: '8px 12px',
        borderRadius: '20px',
        backgroundColor: this.isAmerican ? '#e6f4ea' : '#148c63',
        color: this.isAmerican ? '#239744' : '#ffffff',
        border: this.isAmerican ? '1px solid #d1e7dd' : '1px solid transparent'
      }
    },
    phoneticBtnStyle() {
      return {
        padding: '8px 12px',
        borderRadius: '20px',
        backgroundColor: 'transparent',
        border: '1px solid transparent'
      }
    },
    title() {
      if (this.showType === 'mastered') {
        return `已掌握单词 （共计 ${this.total} 个）`
      }
      if (this.showType === 'learning') {
        return `正在学习单词 （共计 ${this.total} 个）`
      }
      if (this.showType === 'forgotten') {
        return `遗忘单词 （共计 ${this.total} 个）`
      }
    }
  },
  watch: {
    nowClickWord(newValue, oldValue) {
      if (newValue.id !== oldValue.id) {
        oldValue.clickCount = 0
      }
    },
  },
  onLoad(options) {
    this.showType = options.type
    this.page.pageNum = 1
    this.displayedWords = []
    this.finished = false
    this.loadWordData()
  },
  methods: {
    showPhraseExample(word) {
      this.drawer = true
      this.currentWordDetail = word
    },

    async deleteCollectWord(word) {
      const res = await deleteCollectById({id: word.id})
      if (res){
        this.displayedWords = this.displayedWords.filter(item => item.id !== word.id)
      }
    },

    async loadMore() {
      if (this.finished || this.loading) return
      this.page.pageNum += 1
      await this.loadWordData(true)
    },

    async loadWordData(isLoadMore = false) {
      if (this.loading) return
      this.loading = true

      try {
        const res = await getWordListByType(this.showType, {page: this.page}, {})
        const studyWordList = res.records || []
        this.total = Number(res.total) || 0

        studyWordList.forEach(item => {
          item.clickCount = 0
          item.status = ''
        })

        // ✅ 判断是首次加载还是加载更多
        if (isLoadMore) {
          this.displayedWords = [...this.displayedWords, ...studyWordList]
        } else {
          this.displayedWords = studyWordList
        }

        // ✅ 是否加载完
        if (this.displayedWords.length >= this.total) {
          this.finished = true
        }
      } catch (e) {
        console.error('加载失败', e)
      } finally {
        this.loading = false
      }
    },

    async submitCheckData() {
      const idArr = []
      this.displayedWords.forEach(item => {
        if (item.status === 'unknown') {
          idArr.push(item.libraryTypeWordId)
        }
      })
      await antiForgetListPush(
          {
            antiForgetId: this.antiForgetId,
            cid: this.cid
          },
          idArr
      )

      uni.redirectTo({
        url: `/pages/system-frame`
      })
    },

    toggleAccent() {
      this.isAmerican = !this.isAmerican
    },

    togglePhonetic() {
      this.showPhonetic = !this.showPhonetic
    },

    playPronunciation(word) {
      AudioCacheUtil.play(word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : 'I don\'t know', this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
      word.clickCount++
      this.nowClickWord = word
    },

    playZh(text) {
      AudioCacheUtil.play(text, 'zh', this.playbackSpeed)
    },

    playEn(text) {
      AudioCacheUtil.play(text, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
    },
  }
}
</script>

<style scoped>
* {
  user-select: none;
}

.word-learning-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 50px);
  width: 100vw;
  overflow: hidden;
  background-color: #f5f7fa;
}

/* 中间单词列表区域 */
.word-list-container {
  flex: 1;
  overflow: hidden;
  padding: 5px;
}

.word-list {
  height: 100%;
}

.word-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  user-select: none;
}

.word-main {
  flex: 1;
}

.word-text {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  width: 100%;
  position: relative;
}

.word-text text {
  cursor: pointer;
}

.word-phonetic {
  font-size: 18px;
  color: #999;
  margin: 10px 0 0 0;
  font-style: italic;
  display: block;
}

.word-meaning {
  color: #555;
  margin-top: 20px;
}

.word-meaning text {
  cursor: pointer;
}

.phrase-btn-wrap {
  display: flex;
  margin: 0 8px;
  gap: 5rpx;
  font-size: 40rpx;

  * {
    cursor: pointer;
  }
}

.fa-book-open{
  color: #206a95;
}

.fa-delete-left {
  color: #ff4d4f;
}

/* 顶部导航栏整体样式 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 50px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  position: relative;
}

.top-nav__right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.nav-btn {
  border-radius: 20px;
  background-color: transparent;
  color: #333;
  border: 1px solid transparent;
  font-size: 14px;
}

.phonetic-label {
  width: 32px;
  position: relative;
  display: inline-block;
  padding: 0 2px;
  color: #333;
  transition: color 0.2s ease;
}

.phonetic-label::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  height: 2px;
  top: 50%;
  transform: translateY(-50%) scaleX(0);
  transform-origin: left center;
  background: #ff4d4f;
  transition: transform 0.25s cubic-bezier(.2, .9, .2, 1);
  pointer-events: none;
}

.phonetic-label.is-off {
  color: #999;
}

.phonetic-label.is-off::after {
  transform: translateY(-50%) scaleX(1);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.word-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 10px;
  margin-top: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.word-item.word-known {
  background-color: #e6f7ed;
  border: 1px solid #239744;
}

.word-item.word-unknown {
  background-color: #fde2e2;
  border: 1px solid #e53e3e;
}

.word-actions > view {
  position: relative;
  font-size: 40px;
}

.word-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #00b578;
}

.word-item:hover text,
.word-item:hover .word-text {
  color: white;
}
</style>
